/*
 * List.cpp
 *
 *  Created on: 04/04/2009
 *      Author: santiago
 */

#include "List.h"

List::List() {
	this->head = NULL;
	this->size = 0;
}

List::~List() {
	while(!empty()) {
		Node* node = remove(0);
		delete node;
	}
}

void List::add(Node* item) {
	if (!this->head) {
		this->head = item;
		this->size++;
		return;
	}
	Node* node = this->head;
	while (node->getNext()) {
		node = node->getNext();
	}
	node->setNext(item);
	this->size++;
}


int List::getSize() const {
	return size;
}

Node* List::get(int index) const{
	if (index >= getSize()) {
		return NULL;
	}
	int i = 0;
	Node* node = this->head;
	while (node->getNext() && i != index) {
		node = node->getNext();
		i++;
	}
	return node;
}

Node* List::remove(int index) {
	if (index >= this->size) {
		return NULL;
	}
	int i = 0;
	Node* node = this->head;
	Node* tNode = NULL;

	if (index == 0) {
		if (node->getNext()) {
			this->head = node->getNext();
		} else {
			this->head = NULL;
		}
		this->size--;
		return node;
	}

	while (node->getNext() && i < index - 1) {
		node = node->getNext();
		i++;
	}

	tNode = node->getNext();

	if (tNode->getNext()) {
		node->setNext(tNode->getNext());
	} else {
		node->setNext(NULL);
	}

	this->size--;
	return tNode;
}

bool List::empty() const {
	if (size == 0) {
		return 1;
	}
	return 0;
}

List::List(const List& list) {
	for (int i = 0; i < getSize(); i++) {
		this->add(list.get(i)->clone());
	}
}

List& List::operator=(const List& list) {
	for (int i = 0; i < getSize(); i++) {
		this->add(list.get(i)->clone());
	}
	return *this;
}

int List::getIndexOf(Node* node) const {
	if (&node == NULL) {
		return -1;
	}
	for (int i = 0; i < getSize(); i++) {
		if (get(i) == node) {
			return i;
		}
	}
	return -1;
}
